package leetcode;

import entity.ListNode;
import org.junit.Test;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 7/26/2022 8:43 AM
 */
public class Test19 {

    @Test
    public void test() {
        ListNode l1 = new ListNode(1, new ListNode(2, new ListNode(4)));
        removeNthFromEnd(l1, 3);
    }

    /**
     * 删除倒数第 n 个节点
     *
     * @param head node
     * @param n    n
     * @return ListNode
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode tempListNode = new ListNode(0, head);
        // length = 3
        int length = getLength(tempListNode);
        ListNode cur = tempListNode;
        // 从 1 开始
        for (int i = 1; i < length - n + 1; i++) {
            // 找到倒数第 n 个节点
            cur = cur.next;
        }
        // 倒数第 n 个节点的后继等于 第 n 个节点后继的后继
        cur.next = cur.next.next;
        return tempListNode.next;
    }

    /**
     * 计算链表的长度
     *
     * @param tempListNode tempListNode
     * @return int
     */
    private int getLength(ListNode tempListNode) {
        int i = 0;
        ListNode current = tempListNode;
        while (current.next != null) {
            i++;
            current = current.next;
        }
        return i;
    }

}
